package cn.com.yang.java6;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
/**
 * @Author 杨亿金
 * @Date 2022/7/9 23:58
 * @CopyRight
 * @Version
 */
public class TestSystemTray extends JFrame{

    public TestSystemTray(){
        setTitle("选项卡面板");
        this.setBounds(400,400,400,400);
        this.setVisible(true);
        final JLabel label = new JLabel();
        label.setForeground(Color.black);//设置标签前景色
        label.setFont(new Font("微软雅黑", Font.BOLD, 16));//设置标签字体，大小，加粗
        label.setHorizontalAlignment(SwingConstants.CENTER);//设置标签内容居中对齐
        label.setText("请查看系统托盘中的变化！");
        add(label);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void tray(){
        //判断系统是否支持托盘图标
        if(SystemTray.isSupported()){
            URL location = this.getClass().getResource("lufei.jpg");
            ImageIcon icon = new ImageIcon(location);
            PopupMenu pop = new PopupMenu();//创建弹出式菜单
            MenuItem menu = new MenuItem("退出");//创建菜单项
            menu.addActionListener(new ActionListener() {//给菜单项添加事件监听器，单击时退出系统
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
            pop.add(menu);
            TrayIcon tray = new TrayIcon(icon.getImage(),"Icon",pop);

            // 获得系统托盘对象
            SystemTray systemTray = SystemTray.getSystemTray();
            try {
                systemTray.add(tray);// 将托盘图片添加到系统托盘中
            } catch (AWTException e1) {
                e1.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TestSystemTray tst = new TestSystemTray();
        tst.tray();
    }
}
